
const tableName = "BillTypes";
let getTypes = (uid, isIncome, cb) => {
  let Type = new wx.BaaS.TableObject(tableName),
    query = new wx.BaaS.Query(),
    query2 = new wx.BaaS.Query()

  query.compare('created_by', '=', uid)
  if (isIncome != null) {
    query.compare('is_income', '=', isIncome)
  }
  query.compare('is_delete', '=', false)

  query2.compare("is_public", "=", true)
  if (isIncome != null) {
    query2.compare('is_income', '=', isIncome)
  }
  let orQuery = wx.BaaS.Query.or(query, query2)
  Type.setQuery(orQuery).limit(1000).find()
    .then(res => cb(res))
    .catch(err => console.dir(err))
}

let addType = (type_name, is_income, type_icon, cb) => {
  let Types = new wx.BaaS.TableObject(tableName),
    Type = Types.create()

  let data = {
    type_name: type_name,
    is_income: is_income,
    type_icon: type_icon
  }

  Type.set(data)
    .save()
    .then(res => cb(res))
    .catch(err => console.dir(err))

}

let updateType = (id, type_name, is_income, type_icon, cb) => {
  let Types = new wx.BaaS.TableObject(tableName),
    Type = Types.getWithoutData(id)

  let data = {
    type_name: type_name,
    is_income: is_income,
    type_icon: type_icon
  }

  Type.set(data)
      .update()
      .then(res => cb(res))
      .catch(err => console.dir(err))
  }

  let deleteType = (id, cb) => {
    let Types = new wx.BaaS.TableObject(tableName),
      Type = Types.getWithoutData(id)

    let data = {
      is_delete: true
    }

    Type.set(data)
      .update()
      .then(res => cb(res))
      .catch(err => console.dir(err))

    // let Types = new wx.BaaS.TableObject(tableName)

    // Types.delete(id)
    //   .then(res => cb(res))
    //   .catch(err => console.dir(err))
  }

  module.exports = {
    getTypes,
    addType,
    updateType,
    deleteType,
  }